{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Example of HMM-LDA "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import logging\n",
    "from ptm.nltk_corpus import get_reuters_token_list_by_sentence\n",
    "from ptm import HMM_LDA\n",
    "from ptm.utils import get_top_words\n",
    "\n",
    "logger = logging.getLogger('HMM_LDA')\n",
    "logger.propagate=False"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Read corpus"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`corpus` is a nested list of documents, sentences, and word tokens, respectively."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Vocabulary size 3851\n"
     ]
    }
   ],
   "source": [
    "n_docs = 1000\n",
    "voca, corpus = get_reuters_token_list_by_sentence(num_doc=n_docs)\n",
    "print('Vocabulary size', len(voca))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Training HMM LDA"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "n_docs = len(corpus)\n",
    "n_voca = len(voca)\n",
    "n_topic = 50\n",
    "n_class = 20\n",
    "max_iter = 100\n",
    "alpha = 0.1\n",
    "beta = 0.01\n",
    "gamma = 0.1\n",
    "eta = 0.1\n",
    "model = HMM_LDA(n_docs, n_voca, n_topic, n_class, alpha=alpha, beta=beta, gamma=gamma, eta=eta, verbose=False)\n",
    "model.fit(corpus, max_iter=max_iter)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Print Top 10 words for each class and topic"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Topic 0 :  will,on,its,must,throughout,same,by,traditional,loss,background\n",
      "Topic 1 :  future,should,are,charge,higher,sulphur,first,an,company,letter\n",
      "Topic 2 :  ready,same,be,basis,it,will,for,at,registered,capital\n",
      "Topic 3 :  alone,great,specialty,would,unreasonable,falling,say,formed,top,declined\n",
      "Topic 4 :  offer,do,although,on,over,would,much,by,fiscal,objective\n",
      "Topic 5 :  barring,did,bearing,may,but,its,narrow,target,leading,same\n",
      "Topic 6 :  for,two,meeting,may,still,at,six,whose,become,marked\n",
      "Topic 7 :  stimulate,each,under,satisfied,at,transition,distribution,activity,for,provision\n",
      "Topic 8 :  is,difficulty,effect,top,from,nine,price,deficit,agreed,only\n",
      "Topic 9 :  for,country,pressure,increasing,will,government,its,quietly,nil,report\n",
      "Topic 10 :  petroleum,per,expectation,pollard,weight,textile,from,cocoa,absorbing,remainder\n",
      "Topic 11 :  should,but,set,shipment,much,term,same,be,practice,its\n",
      "Topic 12 :  offer,present,at,this,they,help,name,an,time,show\n",
      "Topic 13 :  would,rating,current,landing,year,long,market,after,when,its\n",
      "Topic 14 :  six,goods,national,were,commodity,massive,use,merge,confirmed,days\n",
      "Topic 15 :  trade,it,agreement,industry,those,town,from,we,number,with\n",
      "Topic 16 :  other,year,worked,be,give,it,ago,are,proposal,progress\n",
      "Topic 17 :  speculation,it,deficit,its,this,despite,an,up,large,government\n",
      "Topic 18 :  cash,corn,over,preferred,with,about,still,least,association,overseas\n",
      "Topic 19 :  trade,will,is,accrual,consider,similar,pressure,chairman,parcel,with\n",
      "Topic 20 :  trade,current,fault,or,group,week,this,an,half,one\n",
      "Topic 21 :  fiscal,for,turned,tone,similar,average,annual,it,closed,why\n",
      "Topic 22 :  weak,raising,special,contract,profit,by,while,he,would,block\n",
      "Topic 23 :  following,growth,crude,up,an,leading,business,fiscal,floating,impact\n",
      "Topic 24 :  given,another,reserve,contract,harvest,ahead,an,textile,message,dividend\n",
      "Topic 25 :  today,put,but,debt,market,seen,interest,concern,franc,week\n",
      "Topic 26 :  no,from,six,market,particularly,earn,one,measured,tender,suspension\n",
      "Topic 27 :  most,new,are,percentage,definitive,adequate,bread,business,minister,us\n",
      "Topic 28 :  trade,central,chairman,beginning,last,had,condition,when,subject,added\n",
      "Topic 29 :  certain,period,be,nil,end,issue,quarter,billion,vague,investigatory\n",
      "Topic 30 :  expire,market,underground,it,reaction,sharply,together,nil,everything,government\n",
      "Topic 31 :  exercisable,its,federal,growth,both,would,last,long,much,year\n",
      "Topic 32 :  state,unchanged,quarter,increase,want,several,rolled,we,if,for\n",
      "Topic 33 :  trade,with,being,more,is,total,principally,likely,number,margin\n",
      "Topic 34 :  posted,this,share,next,subject,dealer,executive,two,interview,which\n",
      "Topic 35 :  rise,group,friendly,be,sale,it,also,bank,for,or\n",
      "Topic 36 :  based,premium,most,from,number,last,had,fourth,make,also\n",
      "Topic 37 :  yen,stability,they,offering,billion,week,cut,under,trading,this\n",
      "Topic 38 :  nil,about,bill,re,bank,chairman,be,strong,false,closed\n",
      "Topic 39 :  trade,year,operating,line,say,equal,approach,price,search,strength\n",
      "Topic 40 :  cake,be,move,here,budget,were,should,development,shortly,by\n",
      "Topic 41 :  outstanding,exploration,its,government,number,for,all,account,monthly,week\n",
      "Topic 42 :  industrial,them,short,its,loss,be,it,from,concern,each\n",
      "Topic 43 :  had,responsible,an,unit,we,situation,well,ready,field,not\n",
      "Topic 44 :  settle,trading,see,its,from,much,output,interbank,government,for\n",
      "Topic 45 :  trade,situation,because,cost,priced,but,as,would,its,urgency\n",
      "Topic 46 :  am,major,sugar,pose,t,by,memorandum,dropping,division,were\n",
      "Topic 47 :  who,two,spokesman,cash,loss,kept,it,month,equity,daily\n",
      "Topic 48 :  saw,he,gallon,would,we,sale,season,for,year,not\n",
      "Topic 49 :  permit,be,billion,they,by,concerned,forward,overall,if,from\n"
     ]
    }
   ],
   "source": [
    "for ti in range(n_topic):\n",
    "    top_words = get_top_words(model.TW, voca, ti, n_words=10)\n",
    "    print('Topic', ti ,': ', ','.join(top_words))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Class 1 :  were,on,per,be,it,will,an,is,year,company\n",
      "Class 2 :  at,was,have,billion,not,an,is,will,it,be\n",
      "Class 3 :  trade,will,on,is,loss,be,have,it,from,this\n",
      "Class 4 :  by,also,would,for,will,were,this,have,are,from\n",
      "Class 5 :  the,about,be,on,year,company,would,by,with,loss\n",
      "Class 6 :  the,he,billion,is,be,it,will,an,not,at\n",
      "Class 7 :  the,he,from,were,an,loss,be,it,will,nil\n",
      "Class 8 :  one,with,for,company,an,nil,billion,it,be,loss\n",
      "Class 9 :  the,be,as,was,not,will,it,nil,at,an\n",
      "Class 10 :  on,last,for,at,company,will,it,billion,be,by\n",
      "Class 11 :  the,year,for,would,from,was,be,it,will,an\n",
      "Class 12 :  or,are,it,will,for,not,at,billion,by,its\n",
      "Class 13 :  as,is,not,company,were,will,it,be,loss,at\n",
      "Class 14 :  was,its,it,be,quarter,for,billion,from,would,on\n",
      "Class 15 :  market,last,is,with,on,would,share,by,billion,be\n",
      "Class 16 :  last,on,an,its,loss,be,it,will,company,is\n",
      "Class 17 :  the,trade,this,be,was,it,will,company,for,not\n",
      "Class 18 :  the,last,will,from,billion,an,loss,be,it,its\n",
      "Class 19 :  the,of,to,in,said,and,a,for,s,on\n"
     ]
    }
   ],
   "source": [
    "for ci in range(1, n_class):\n",
    "    top_words = get_top_words(model.CW, voca, ci, n_words=10)\n",
    "    print('Class', ci ,': ', ','.join(top_words))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Function words belong to classes and content words belong to topics.**\n",
    "\n",
    "In this example, function words are not very well divided by their roles. As in the original paper, fine-tuning, sampling hyper-parameters or n-th order Markovian assumption may help to improve the performance."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.4.3"
  },
  "toc": {
   "toc_cell": true,
   "toc_number_sections": true,
   "toc_threshold": 4,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
